package com.lyb.spzx.order.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lyb.common.utils.AuthContextUtil;
import com.lyb.spzx.common.exception.DefinedException;
import com.lyb.spzx.feign.cart.CartFeignClient;
import com.lyb.spzx.feign.product.ProductFeignClient;
import com.lyb.spzx.feign.user.UserFeignClient;
import com.lyb.spzx.model.dto.h5.OrderInfoDto;
import com.lyb.spzx.model.dto.system.system.user.UserAddress;
import com.lyb.spzx.model.dto.system.system.user.UserInfo;
import com.lyb.spzx.model.entity.h5.CartInfo;
import com.lyb.spzx.model.entity.order.OrderInfo;
import com.lyb.spzx.model.entity.order.OrderItem;
import com.lyb.spzx.model.entity.product.ProductSku;
import com.lyb.spzx.model.vo.common.ResultCodeEnum;
import com.lyb.spzx.model.vo.h5.TradeVo;
import com.lyb.spzx.order.mapper.OrderInfoMapper;
import com.lyb.spzx.order.mapper.OrderItemMapper;
import com.lyb.spzx.order.service.OrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderInfoServiceImpl implements OrderInfoService {

    @Autowired
    CartFeignClient cartFeignClient;

    @Autowired
    ProductFeignClient productFeignClient;

    @Autowired
    UserFeignClient userFeignClient;

    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Override
    public TradeVo trade() {
        //查询所有勾选的商品
        List<CartInfo> allCkecked = cartFeignClient.getAllCkecked();
        List<OrderItem> orderItemList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(allCkecked)){
            for (CartInfo cartInfo:allCkecked) {
                OrderItem orderItem = new OrderItem();
                orderItem.setSkuId(cartInfo.getSkuId());
                orderItem.setSkuName(cartInfo.getSkuName());
                orderItem.setSkuNum(cartInfo.getSkuNum());
                orderItem.setSkuPrice(cartInfo.getCartPrice());
                orderItem.setThumbImg(cartInfo.getImgUrl());
                orderItemList.add(orderItem);
            }

        }

        //计算总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList){
            totalAmount = totalAmount
                    .add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }

        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }

    @Override
    public Long submitOrder(OrderInfoDto orderInfoDto) {
        //数据校验
        List<OrderItem> orderItemList = orderInfoDto.getOrderItemList();
        if (CollectionUtils.isEmpty(orderItemList)){
            throw new DefinedException(ResultCodeEnum.DATA_ERROR);
        }

        //遍历循环，查找每一条数据的sku
        for (OrderItem orderItem : orderItemList) {
            ProductSku productSku = productFeignClient.getBySkuId(orderItem.getSkuId());
            if (productSku == null){
                throw new DefinedException(ResultCodeEnum.DATA_ERROR);
            }
            //校验库存
            if (orderItem.getSkuNum().intValue() > productSku.getStockNum().intValue()){
                throw new DefinedException(ResultCodeEnum.STOCK_LESS);
            }
        }

        //构建订单数据，保存订单
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setNickName(userInfo.getNickName());
        orderInfo.setOrderNo(String.valueOf(System.currentTimeMillis()));
        orderInfo.setUserId(userInfo.getId());
        //获取用户收货地址
        UserAddress userAddress = userFeignClient.getUserAddressById(orderInfoDto.getUserAddressId());
        orderInfo.setReceiverName(userInfo.getNickName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverAddress(userAddress.getAddress());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverCity(userAddress.getCityCode());

        //订单金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount
                    .add(orderItem.getSkuPrice()
                            .multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderInfoDto.getFeightFee());
        orderInfo.setPayType(2);
        orderInfo.setOrderStatus(0);
        orderInfo.setRemark(orderInfoDto.getRemark());
        orderInfoMapper.save(orderInfo);

        //保存订单明细
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(userInfo.getId());
            orderItemMapper.insert(orderItem);
        }

        //清空购物车提交过的订单
        cartFeignClient.deleteChecked();
        return orderInfo.getId();
    }

    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        return orderInfoMapper.selectOrderInfoByOrderId(orderId);
    }

    @Override
    public TradeVo buy(Long skuId) {
        //查询商品
        ProductSku productSku = productFeignClient.getBySkuId(skuId);
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuNum(1);
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItem.setSkuName(productSku.getSkuName());
        orderItemList.add(orderItem);

        //计算总金额
        BigDecimal totalAmount = productSku.getSalePrice();
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }

    @Override
    public PageInfo<OrderInfo> getAllTrade(Integer page, Integer limit, Integer orderStatus) {
        PageHelper.startPage(page,limit);
        //获取用户登录信息
        Long userId = AuthContextUtil.getUserInfo().getId();
        List<OrderInfo> orderInfoList = orderInfoMapper.findUserByPage(userId, orderStatus);

        orderInfoList.forEach(orderInfo -> {
            List<OrderItem> orderItemList = orderItemMapper.findByOrderId(orderInfo.getId());
            orderInfo.setOrderItemList(orderItemList);
        });

        return new PageInfo<>(orderInfoList);
    }

    @Override
    public OrderInfo getOrderInfoByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.findByOrderNo(orderNo);
        List<OrderItem> orderItemList = orderItemMapper.findByOrderId(orderInfo.getId());
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Override
    public void updateOrderStatus(String orderNo, Integer payType) {
        //更新订单状态
        OrderInfo orderInfo = orderInfoMapper.findByOrderNo(orderNo);
        orderInfo.setOrderNo(orderNo);
        orderInfo.setPayType(payType);
        orderInfo.setUpdateTime(new Date());
        orderInfoMapper.updateById(orderInfo);


    }
}
